//
//  MyAppointmentViewController.m
//  WeiWeiApp
//
//  Created by 高继鹏 on 15/10/15.
//  Copyright © 2015年 GaoJipeng. All rights reserved.
//

#import "MyAppointmentViewController.h"
#import "QZOrderCell.h"
#import "QZDesignerCell.h"
#import "QZAppointBottomView.h"
#import "QZAddressViewController.h"
#import "QZSeleteTimeView.h"
#import "QZDatePickerViewController.h"
#import "PersonInfoViewController.h"
#import "QZMyAppointVc.h"
#import "QZChoiceBranchVc.h"
#import "PayMoneyViewController.h"
#import "QZServiceItemsVc.h"
#import "QZPositionVc.h"
#import "QZChoiceHairStylistVc.h"
#import "StoreModel.h"
#import "DesignerModel.h"
#import "AppointmentModel.h"
#import "QZDateManager.h"
@interface MyAppointmentViewController ()

@end

@implementation MyAppointmentViewController
{
    UIView *_grayView;
    QZSeleteTimeView *_seleteTimeView;
    QZDatePickerViewController *_picker;
    
    NSMutableString *_serveType;//服务项目
    NSMutableArray *_serveIds;//服务项目id
    NSArray *_seletedServeArr;
    
    NSString *_serveLoction;//位置
    
    NSString *_seleteDateTime;//预约时间
    NSString *_seleteAddress;//预约地点
    StoreModel *_addressPointAnnot;//地点
    DesignerModel *_designerInfo;//设计师信息
    UILabel *_appointPay;//押金
    
    NSArray *_rightArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _serveType = [[NSMutableString alloc]init];
    _serveIds = [[NSMutableArray alloc]init];
    
    self.navigationItem.title = @"预约";
    
    [self addBtnOnNavWithTitle:@"我的预约" andImageName:nil andTarget:self andAction:@selector(myAppiont) andFrame:CGRectMake(0, 0, 65, 20) andDirection:right];
    
    [self createTableViewWithPlainStyle:NO andSeparatorStyleNone:NO andBackGroudImageName:nil];
    [self registCellWithNib:@"QZOrderCell" addIdentifier:@"orderCell" addHeight:44];
    [self registCellWithNib:@"QZDesignerCell" addIdentifier:@"designerCell" addHeight:80];
    
    [self loadData];
    
    [self createFooterView];
    [self createGrayView];
    [self createSeleteTimeView];
    [self createPickerView];
    [self addYaJin];//获取押金
}
-(void)viewWillAppear:(BOOL)animated{
    [self addYaJin];//获取押金
    
}
-(void)addYaJin{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"HairOrder.GetHairOrderMargin"];
    self.request.isShowHUD = NO;
    [self.request QZRequest_POST:url parameters:nil tagNSString:@"获取押金" stopRequest:NO isSerializer:NO isCache:YES];
}
-(void)myAppiont
{
    QZMyAppointVc *infoVc = [[QZMyAppointVc alloc]init];
    infoVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:infoVc animated:YES];
}

-(void)createPickerView
{
    _picker = [[QZDatePickerViewController alloc]init];
    _picker.view.backgroundColor = [UIColor yellowColor];
    _picker.datePicker.backgroundColor = [UIColor whiteColor];
    
    _seleteTimeView.pickerView = _picker.view;
    _picker.datePicker.frame = _seleteTimeView.pickerView.frame;
    _picker.mainColor = [UIColor blackColor];
    _picker.showLabel = _seleteTimeView.dateLabel;
}
-(void)createGrayView
{
    UIView *grayView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    grayView.backgroundColor = [UIColor blackColor];
    grayView.alpha = 0.5;
    grayView.hidden = YES;
    [self.view addSubview:grayView];
    _grayView = grayView;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [_grayView addGestureRecognizer:tap];
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    _grayView.hidden = YES;
    _seleteTimeView.hidden = YES;
}
-(void)createSeleteTimeView
{
    _seleteTimeView = [[[NSBundle mainBundle]loadNibNamed:@"QZSeleteTimeView" owner:self options:nil]lastObject];
    _seleteTimeView.frame = CGRectMake(0, 80+64, WIDTH, 250);
    _seleteTimeView.hidden = YES;
    [_seleteTimeView.sureBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    [_seleteTimeView.cancleBtn addTarget:self action:@selector(cancleAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_seleteTimeView];
}
-(void)cancleAction:(UIButton *)btn
{
    [self tapAction:nil];
}
-(void)sureAction:(UIButton *)btn
{
    _seleteDateTime = _seleteTimeView.dateLabel.text;
    [self.tableView reloadData];
    [self tapAction:nil];
}
-(void)createFooterView
{
    QZAppointBottomView *bottom = [[[NSBundle mainBundle]loadNibNamed:@"QZAppointBottomView" owner:self options:nil]lastObject];
    _appointPay = bottom.appointPay;
    [bottom.appointNowBtn addTarget:self action:@selector(bottomAction:) forControlEvents:UIControlEventTouchUpInside];
    
    bottom.frame = CGRectMake(0, HEIGHT - 64 - 48 - 48, WIDTH, 49);
    [self.view addSubview:bottom];
}
//立即预约
#pragma mark- 立即预约
-(void)bottomAction:(UIButton *)btn
{
    if (_serveType.length == 0) {
        [[iToast makeText:@"服务项目不能为空"] show];
        return;
    }
    if (_serveLoction.length == 0) {
        [[iToast makeText:@"服务方式不能为空"] show];
        return;
    }
    if(_seleteDateTime.length == 0){
        [[iToast makeText:@"时间不能为空"] show];
        return;
    }
    if(_seleteAddress.length == 0){
        [[iToast makeText:@"地点不能为空"] show];
        return;
    }
//    
//    NSIndexPath *path2 = [NSIndexPath indexPathForItem:0 inSection:2];
//    QZDesignerCell *cellDes = [self.tableView cellForRowAtIndexPath:path2];
    if (!_designerInfo && self.tableSource.count>2) {
        [[iToast makeText:@"请选择设计师"] show];
        return;
    }
    CLLocationCoordinate2D coor;
    coor.longitude = _addressPointAnnot.longitude;
    coor.latitude  = _addressPointAnnot.latitude;
    long timeSp = _seleteDateTime?[QZTime getTimeSpetWithDate:[QZTime dateFromString:_seleteDateTime withFormat:@"yyyy年MM月dd日 HH:mm"]]:[QZTime getTimeSpetWithDate:[NSDate date]];
    
//    NSString * timeSp = [[QZDateManager sharedDateManager] stringTimeToSecond:_seleteDateTime];
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"HairOrder.GetHairOrderAdd"];
    
    NSNumber *shop_id = [NSNumber numberWithInteger:_addressPointAnnot.id];
    NSDictionary *dic = nil;
    if ([shop_id integerValue]) {
        
        dic = @{
                @"user_id":[QZUserInfo userId],
                @"appoint_cate":_serveIds,
                @"appoint_type":[_serveLoction isEqualToString:@"店铺"]?@(1):@(2),
                @"appoint_address":_addressPointAnnot.address,
                @"latitude":@(coor.latitude),
                @"longitude":@(coor.longitude),
                @"appoint_time":@(timeSp),
                @"designer_id":@(_designerInfo.id),
                @"shop_id":shop_id
                };
    }else{
        
        dic = @{
                @"user_id":[QZUserInfo userId],
                @"appoint_cate":_serveIds,
                @"appoint_type":[_serveLoction isEqualToString:@"店铺"]?@(1):@(2),
                @"appoint_address":_addressPointAnnot.address,
                @"latitude":@(coor.latitude),
                @"longitude":@(coor.longitude),
                @"appoint_time":@(timeSp),
                @"designer_id":@(_designerInfo.id),
                };
    }
    

    [self.request QZRequest_POST:url parameters:dic tagNSString:@"预约" stopRequest:NO isSerializer:NO isCache:NO];
    
}
-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag
{
    if ([tag isEqualToString:@"预约"]) {
        if ([value[@"data"][@"status"] intValue] == 100) {
            NSDictionary *dic = value[@"data"][@"data"];
            AppointmentModel *model = [[AppointmentModel alloc] initWithDictionary:dic error:nil];
            
            PayMoneyViewController *payVc = [[PayMoneyViewController alloc]init];
            payVc.isAppointment = YES;
            payVc.appModel = model;
            payVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:payVc animated:YES];
        }else{
            [[iToast makeText:@"预约失败"] show];
        }
    }
    if ([tag isEqualToString:@"获取押金"]) {
        if ([value[@"data"][@"status"] intValue] == 100) {
            NSString *margin = value[@"data"][@"data"][@"Margin"];
            if (margin) {
                [[TMCache sharedCache] setObject:margin forKey:@"margin"];
            }
            _appointPay.text = [NSString stringWithFormat:@"￥%@",margin];
        }
    }
}
-(void)loadData
{
    [self.tableSource addObject:@[@"服务项目",@"服务方式"]];
    [self.tableSource addObject:@[@"时间",@"地点"]];
    [self.tableSource addObject:@[@""]];
    
    [self.tableView reloadData];
}
-(void)actionAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0 && indexPath.row == 0) {//服务项目
        QZServiceItemsVc *itemVc = [[QZServiceItemsVc alloc]init];
        itemVc.seletedBlock = ^(id object){
            _seletedServeArr = object;
            [_serveType setString:@""];
            [_serveIds removeAllObjects];
            
            NSArray *arr = object;
            for (int i = 0;i < arr.count;i++) {
                NSDictionary *dic = arr[i];
                if (i == arr.count - 1) {
                    [_serveType appendString:dic[@"name"]];
                }else{
                    [_serveType appendFormat:@"%@,",dic[@"name"]];
                }
                [_serveIds addObject:dic[@"id"]];
            }
            
            [self.tableView reloadData];
        };
        itemVc.lastSeleteItemArr = _seletedServeArr;
        itemVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:itemVc animated:YES];
        return;
    }
    if (indexPath.section == 0 && indexPath.row == 1) {//服务方式
        QZPositionVc *positionVc = [[QZPositionVc alloc]init];
        
        positionVc.seletedBlock = ^(id obj){
            _serveLoction = obj;
            QZOrderCell *cellTmp = [weakSelf.tableView cellForRowAtIndexPath:indexPath];
            cellTmp.rightLabel.text = obj;
            
            NSIndexPath *path = [NSIndexPath indexPathForItem:1 inSection:1];
            QZOrderCell *cell =  [weakSelf.tableView cellForRowAtIndexPath:path];
            
             NSIndexPath *path2 = [NSIndexPath indexPathForItem:0 inSection:2];
//            QZDesignerCell *cellDes = [weakSelf.tableView cellForRowAtIndexPath:path2];
            if ([obj isEqualToString:@"店铺"]) {
               
                cell.leftLabel.text = @"店铺地址";
                if (weakSelf.tableSource.count == 2) {
                    [self.tableSource addObject:@[@""]];
                }
                
            }else{
                cell.leftLabel.text = @"我的位置";
                if (weakSelf.tableSource.count ==3) {
                    [self.tableSource removeLastObject];
                }
                
            }
            [self.tableView reloadData];
        };
        positionVc.lastSeletedContent = _serveLoction;
        positionVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:positionVc animated:YES];
    }
    if (indexPath.section == 1 && indexPath.row == 0) {//时间
        _grayView.hidden = NO;
        _seleteTimeView.hidden = NO;
        return;
    }
    if (indexPath.section == 1 && indexPath.row == 1) {//地点
        if (!_serveLoction) {
            [[iToast makeText:@"请选择服务方式"] show];
            return;
        }
        
        QZChoiceBranchVc *choiceVc = [[QZChoiceBranchVc alloc]init];
        choiceVc.selverStay = _serveLoction;
        choiceVc.seleteBlock = ^(id obj){
            _addressPointAnnot = obj;
            
            _seleteAddress = _addressPointAnnot.name?_addressPointAnnot.name:_addressPointAnnot.address;
            [self.tableView reloadData];
        };
        choiceVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:choiceVc animated:YES];
        return;
    }
    if(indexPath.section == 2){//设计师
        if (!_serveLoction) {
            [[iToast makeText:@"请选择服务方式"] show];
            return;
        }
        if (!_addressPointAnnot) {
            [[iToast makeText:@"请选择地点"] show];
            return;
        }
        QZChoiceHairStylistVc *choiceVc = [[QZChoiceHairStylistVc alloc]init];
        choiceVc.model = _addressPointAnnot;
        choiceVc.storeStay = _serveLoction;
        
        QZDesignerCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        choiceVc.myBlock = ^(DesignerModel *model2){
            _designerInfo = model2;
            [cell.userImage sd_setImageWithURL:[NSURL URLWithString:model2.userimg] placeholderImage:[UIImage imageNamed:@"1123"]];
            cell.nickName.text = model2.nickName;
        };
        choiceVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:choiceVc animated:YES];
        return;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return 44;
    }
    if (indexPath.section == 2) {
        return 80;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    _rightArr = @[@[[QZToString toStringWith:_serveType],[QZToString toStringWith:_serveLoction]],@[[QZToString toStringWith:_seleteDateTime],[QZToString toStringWith:_seleteAddress]]];
    
    if (indexPath.section == 0 || indexPath.section == 1) {
        QZOrderCell *orderCell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
        orderCell.selectionStyle = UITableViewCellSelectionStyleNone;
        orderCell.leftLabel.text = self.tableSource[indexPath.section][indexPath.row];
        orderCell.rightLabel.text = _rightArr[indexPath.section][indexPath.row];
        return orderCell;
    }
    if (indexPath.section == 2) {
        QZDesignerCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"designerCell"];
        dCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return dCell;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.000000001;
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
